const app = getApp()

Page({
  data: {
    aboutUsTitle: '',
    aboutUsContent: '',
    servicePhoneNumber: '1224344555',
    balance: 0,
    freeze: 0,
    score: 0,
    score_sign_continuous: 0,
    iconSize: 45,
    iconColor: '#999999',
    
    usercoupons:0,
    orders0:0,
    orders1:0,
    orders2:0,
    orders3:0,
    isManager:"",
    recommendGoods:[],
    recommendGoodsShow:[],
    isEnd: false, //到底啦
    shopCarInfo:{}//购物车
  },
  onPullDownRefresh: function () {
    var that = this
    wx.showNavigationBarLoading()
    that.onShow()
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  onLoad() {
    let that = this;/***
    let userid = wx.getStorageSync('userid')
    if (!userid) {
      wx.navigateTo({
        url: "/pages/login/index"
      })
    } */
   
     
    that.setData({
      version: app.globalData.version,
      background_color: app.globalData.globalBGColor,
      bgRed: app.globalData.bgRed,
      bgGreen: app.globalData.bgGreen,
      bgBlue: app.globalData.bgBlue
    })
    //查询精品推荐
   // const db = wx.cloud.database()
    
    //db.collection('goods').get({
      //success: res => {
       // that.setData({
       //   "goodsList":res.data
       // })
      //}
    //})
    that.getGoods()
  },
 
  //查询订单状态 优惠券数量 积分
  getCoupons_orderStatus_jifen(){
    let that = this;
    //云函数参数
    var  pam ={
      db:"coupons",
      type:"count",
      data:"",
      indexKey:"",
      condition:{
        _openid: wx.getStorageSync('openid')
      },
      skip:0,
      limit:1000
    }
    wx.cloud.callFunction({
      name: 'usercenter',
      data:pam,
      success: res => {
        console.log(res)
        that.setData({
          usercoupons:res.result.youhuiquan.total,
          orders0:res.result.orders0.total,
          orders1:res.result.orders1.total,
          orders2:res.result.orders2.total,
          orders3:res.result.orders3.total,
        })
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
      }
    })
  },
  //全部订单跳转
  toOrders(){
  wx.navigateTo({
   
    url: '/pages/order/index?type=9999',
  })
  },
 
  changeData:function(){
    console.log("刷新user页面")
    this.onLoad();//最好是只写需要刷新的区域的代码，onload也可，效率低，有点low
    
    },
  onShow() {
    var that = this;
    // 获取购物车数据
    wx.getStorage({
      key: 'shopCarInfo',
      success: function (res) {
        that.setData({
          shopCarInfo: res.data,
          shopNum: res.data.shopNum
        });
      }
    })
    //优惠券-订单状态
    that.getCoupons_orderStatus_jifen()
   that.showuser()
    
  },
  onReady(){
   
  },
  showuser(){
    var that = this;
    var user = wx.getStorageSync('userInfo')
    
    if (user) {
      that.setData({
        userInfo: user,
      })
    }else{
     
    }
  },
  //跳转优惠券
  coupon(){
    wx.navigateTo({
      url: '/pages/ucenter/mycoupons/index',
     
    })
  },
  //邀请新人
  yaoqingxinren(){
    wx.navigateTo({
      url: '../yaoxinren/yaoxinren',
    })
  },
  
  
  //重新登陆
  reLogin: function () {
    wx.removeStorageSync('openid')
    wx.removeStorageSync('userid')
    
    app.globalData.userInfo=""
    wx.navigateTo({
     url: "/pages/login/index"
    })
    
  },
  //积分
  recharge: function () {
    wx.navigateTo({
      url: "/pages/recharge/index"
    })
  },
  //商品详情
  toDetailsTap: function (e) {
    wx.navigateTo({
      url: "/pages/goods-details/index?id=" + e.currentTarget.dataset.id
    })
  },
  withdraw: function () {
    wx.navigateTo({
      url: "/pages/withdraw/index"
    })
  },
  //推荐商品
  getGoods: function () {
    var that = this;
    
     that.setData({
      loadingStatus: true
    })
    
    wx.cloud.callFunction({
      // 云函数名称
      name: 'crud',
      // 传给云函数的参数
      data: {
        db:"goods",
        type:"getall",
        data:"",
        indexKey:"",
        //待筛选的参数-库存 >0
        commandtype:[{
          type:'gt',
          ziduan:'stores',
          value:0
        }],
        condition:{
          status:1,
          recommendStatus:1
        },
      },
    })
    .then(res => {
      console.log(res)
      that.setData({
        goods: [],
      });
      var goods = [];
    
      if(res.result){
        if ( res.result.data.length == 0) {
          that.setData({
            prePageBtn: false,
            nextPageBtn: true,
            toBottom: true
          });
          return;
        }
        let result =  res.result.data
        for (var i = 0; i < result.length; i++) {
          goods.push(result[i]);
        } 
      
        app.globalData.goods = goods
        //  var page = that.data.page;
        // var pageSize = that.data.pageSize;
        /*
        //评价几颗星
        for (let i = 0; i < goods.length; i++) {
          goods[i].starscore = (goods[i].numberGoodReputation / goods[i].numberOrders) * 5
          goods[i].starscore = Math.ceil(goods[i].starscore / 0.5) * 0.5
          goods[i].starpic = starscore.picStr(goods[i].starscore)
        }*/
        that.setData({
          recommendGoods: goods,
        });
   
        that.setData({
          loadingStatus: false,
          loadingFinish: true
        })
        
        that.getRGshow()
        setTimeout(() => {
          that.setData({
            loadingFinish: false
          })
        }, 1500)
    
        }
    })
    .catch(console.error)
  },
  
  //加入购物车
  addShopCar(event){
   
    var id= event.currentTarget.dataset.id;
    //查库存
    const db = wx.cloud.database()
   
    db.collection('goods').where({
      _id: id
    }).get({
      success: res => {
        
        if( res.data[0].stores > 0){
          //组建购物车
          var shopCarInfo = this.bulidShopCarInfo(event);  
          this.setData({
            shopCarInfo: shopCarInfo,
            shopNum: shopCarInfo.shopNum
          });
           // 写入本地存储
          wx.setStorage({
            key: "shopCarInfo",
            data: shopCarInfo
          })
          wx.showToast({
            title: '加入购物车成功',
            icon: 'success',
            duration: 1000
          })
        }else{
          wx.showModal({
            title: '提示',
            content: '库存不足！',
            showCancel: false
          })
          return
        }
      }
    })

  

},
//组件购物车
bulidShopCarInfo: function (event) {
  
  // 加入购物车
  var shopCarMap = {};
  shopCarMap.goodsId = event.currentTarget.dataset.id;
  shopCarMap.pic = event.currentTarget.dataset.pic;
  shopCarMap.name = event.currentTarget.dataset.name;
  // shopCarMap.label=this.data.goodsDetail.id; 规格尺寸 
  shopCarMap.propertyChildIds = event.currentTarget.dataset.propertychildids  ||"";
//  shopCarMap.label = this.data.propertyChildNames;
    shopCarMap.price = event.currentTarget.dataset.minprice;
  shopCarMap.left = "";
  shopCarMap.active = true;
  shopCarMap.number =1 ;// this.data.buyNumber;
//  shopCarMap.logisticsType = this.data.goodsDetail.logisticsId;
 // shopCarMap.logistics = this.data.goodsDetail.logistics;
  //shopCarMap.weight = this.data.goodsDetail.weight;

 // 获取购物车数据
  var shopCarInfo = this.data.shopCarInfo;
  if (!shopCarInfo.shopNum) {
    shopCarInfo.shopNum = 0;
  }
  if (!shopCarInfo.shopList) {
    shopCarInfo.shopList = [];
  }
  var hasSameGoodsIndex = -1;
  for (var i = 0; i < shopCarInfo.shopList.length; i++) {
    var tmpShopCarMap = shopCarInfo.shopList[i];
    
    if (tmpShopCarMap.goodsId == shopCarMap.goodsId && tmpShopCarMap.propertyChildIds == shopCarMap.propertyChildIds) {
      hasSameGoodsIndex = i;
      shopCarMap.number = shopCarMap.number + tmpShopCarMap.number;
      break;
    }
  }
  //总数量 =1
  shopCarInfo.shopNum = shopCarInfo.shopNum + 1;
  if (hasSameGoodsIndex > -1) {
    shopCarInfo.shopList.splice(hasSameGoodsIndex, 1, shopCarMap);
  } else {
    shopCarInfo.shopList.push(shopCarMap);
  }
  //shopCarInfo.kjId = this.data.kjId;
 
  return shopCarInfo;
},
//打电话
makePhoneCall: function () {
  var that = this;
  wx.makePhoneCall({
    phoneNumber: that.data.servicePhoneNumber,
    success: function (res) { },
    fail: function (res) {
      wx.showModal({
        title: '呼叫失败',
        content: '请稍后再试',
        showCancel: false,
      })
    },
    complete: function (res) { },
  })
},
   //精品推荐分页展示
   getRGshow: function () {
    
    console.log("加载下页")
    var that = this;
    if (that.data.isEnd) {
      console.log('isEnd, return...')
      return;
    }
    console.log('notEnd, continue')
    that.setData({
      loadingMore: true
    })
    var pageSize = 10; //一次加载万所有的推荐商品，避免minui显示问题that.data.recommendGoods.length
    var recommendGoodsShow = that.data.recommendGoodsShow;
    var rgShowLen = recommendGoodsShow.length;
  
   
      if (rgShowLen + pageSize <= that.data.recommendGoods.length) {
        for (var i = rgShowLen; i < rgShowLen + pageSize; i++) {
          recommendGoodsShow.push(that.data.recommendGoods[i])
       }

      
      that.setData({
        recommendGoodsShow: recommendGoodsShow
      })

      if (recommendGoodsShow.length < that.data.recommendGoods.length) {
        that.setData({
          loadingMore: false,//关闭遮罩层
        })
      } else {
        that.setData({
          loadingMore: false,//关闭遮罩层
          isEnd: true
        })
      }
     
    } else if (rgShowLen < that.data.recommendGoods.length) {
      for (var i = rgShowLen; i < that.data.recommendGoods.length; i++) {
        recommendGoodsShow.push(that.data.recommendGoods[i])
      }
      //虚拟加载特效

      that.setData({
        recommendGoodsShow: recommendGoodsShow,
        loadingMore: false,//关闭遮罩层
        isEnd: true//显示没有了提示
      })

      
    }
  },
  onReachBottom: function(){
    console.log("上拉加载分页")
    var that = this
    that.getRGshow()
  },
})